const Parse = require('parse/node')

register('Finder')
register('Test')

// implementation details
let counterCache = {}

function register (className) {
  loadingCache(className)
  Parse.Cloud.beforeSave(className, autoIncrement)
}

function autoIncrement (req, res) {
  var obj = req.object
  if (Number(counterCache[obj.className])) {
    increment(obj)
    res.success(obj)
  } else {
    loadingCache(obj.className).then(() => {
      increment(obj)
      res.success(obj)
    })
  }
}

function increment (obj) {
  var cache = Number(counterCache[obj.className])
  cache++
  counterCache[obj.className] = cache
  obj.set('autoIncrement', cache)
  return obj
}

function loadingCache (className) {
  return new Parse.Query(className).count(c => {
    counterCache[className] = Number(c)
    return c
  })
}
